﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ForcePoolMembersOfflineCommand.cs" company="CET">
//   The Center of Educational Technology
// </copyright>
// <summary>
//   Defines the LoadPoolsCommand type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace F5.BigIp.LocalTrafficManager.UI.Commands
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows;
    using System.Windows.Input;

    using F5.BigIp.LocalTrafficManager.Interfaces;
    using F5.BigIp.LocalTrafficManager.Proxy.V11;

    /// <summary>
    /// The load pools command.
    /// </summary>
    public class ForcePoolMembersOffline : PoolMemberCommand, ICommand
    {
        public ForcePoolMembersOffline(IPoolMemberService poolMemberService)
            : base(poolMemberService)
        {
        }

        /// <summary>
        /// The can execute changed.
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        /// <summary>
        /// The can execute.
        /// </summary>
        /// <param name="parameter">
        /// The parameter.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public bool CanExecute(object parameter)
        {
            var poolMembers = parameter as IEnumerable<IPoolMember>;

            return this.PoolMemberService != null &&
                   poolMembers != null &&
                   poolMembers.Any(k => k.Status != PoolMemberStatus.Offline);
        }

        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="parameter">
        /// The parameter.
        /// </param>
        public void Execute(object parameter)
        {
            var poolMembers = parameter as IList<IPoolMember>;

            if (poolMembers == null)
            {
                return;
            }

            var result = MessageBox.Show("Are you sure you want to Force Offline?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            foreach (var poolMember in poolMembers.Where(k => k.Status != PoolMemberStatus.Offline))
            {
                this.PoolMemberService.ForcePoolMemberOffline(poolMember);
            }
        }
    }
}
